package com.gitee.feizns.explore.data_structure.tree.bs.mid;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

/**
 * 1123. 最深叶节点的最近公共祖先
 * @author feizns
 * @since 2020/3/17
 */
public class LcaDeepestLeaves {

    public static void main(String[] args) {

    }

    public TreeNode lcaDeepestLeaves(TreeNode root) {
        if ( root != null ) {
            Map<TreeNode, TreeNode> parents = new HashMap<>();
            Set<TreeNode> levelNodes = null;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while ( !queue.isEmpty() ) {
                int size = queue.size();
                levelNodes = new HashSet<>();
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.remove();
                    levelNodes.add(node);
                    if ( node.left != null ) {
                        queue.add(node.left);
                        parents.put(node.left, node);
                    }
                    if ( node.right != null ) {
                        queue.add(node.right);
                        parents.put(node.right, node);
                    }
                }
            }
            while ( levelNodes.size() != 1 ) {
                Set<TreeNode> p = new HashSet<>();
                for (TreeNode node : levelNodes) {
                    TreeNode parent = parents.get(node);
                    if ( parent == null )
                        return node;
                    p.add(parent);
                }
                levelNodes = p;
            }
            return levelNodes.iterator().next();
        }
        return null;
    }

}
